package com.love_weinuo.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.maps.model.TileOverlay;
import com.amap.api.maps.model.TileOverlayOptions;
import com.amap.api.maps.model.UrlTileProvider;
import com.love_weinuo.R;
import com.love_weinuo.bean.LandListCallBackBean;
import com.love_weinuo.bean.Location;
import com.love_weinuo.databinding.ActivityShowLandDescBinding;
import com.love_weinuo.ui.BaseActivity;
import com.love_weinuo.util.BHThreadPool;
import com.love_weinuo.util.CenterPointUtil;
import com.love_weinuo.util.GsonUtil;
import com.love_weinuo.util.LogUtil;
import com.love_weinuo.util.PermissionUtil;
import com.love_weinuo.util.SpUtils;
import com.love_weinuo.util.dialog.InputLandNameDialog;
import com.love_weinuo.util.listener.OnLandNameInputListener;
import com.love_weinuo.util.maputil.MapImageCache;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.love_weinuo.bean.Constants.LOGINPRESSION;
import static com.love_weinuo.bean.Constants.REQEEST_CDOE_GPS;

/**
 * Created by Administrator on 2019/3/20.
 */

public class ShowLandDescActivity extends BaseActivity {

    LandListCallBackBean.ResultEntity.ResEntity bean;
    boolean isShow = true;
    Location location = new Location();
    AMapLocationClient mLocationClient = null;
    AMapLocationClientOption mLocationOption = null;
    MyAMapLocationListener listener = new MyAMapLocationListener();
    MapView mMapView = null;
    AMap aMap;
    ActivityShowLandDescBinding binding;
    public TextView btn_start, btn_extract, btn_undo, btn_end;
    public TextView textView_map;
    public List<LatLng> listGps = new ArrayList<>();//gps坐标集合
    public List<LatLng> listBGps = new ArrayList<>();//点击的gps标点集合 TODO
    public List<Polyline> listLine = new ArrayList<>();//线段集合
    public boolean tag = false;
    //图片缓存地址
    private final static String ALBUM_PATH = Environment.getExternalStorageDirectory() + "/amapdemo/Cache/";
    private TileOverlay mtileOverlay;
    String userId = (String) SpUtils.get("module_user_id", "");
    //土地坐标
    List<LatLng> lists = new ArrayList();
    List<LatLng> listSecond = new ArrayList();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_show_land_desc);
        binding.setActivity(this);
        mMapView = findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);
        initView();
    }

    private void initView() {
        add(this);
        bean = (LandListCallBackBean.ResultEntity.ResEntity) getIntent().getSerializableExtra("module_land_bean");
        initPermission();
        setTitleText("我的土地");
        btn_start = findViewById(R.id.btn_start);
        btn_extract = findViewById(R.id.btn_extract);
        btn_undo = findViewById(R.id.btn_undo);
        btn_end = findViewById(R.id.btn_end);
        textView_map = findViewById(R.id.textView_map);
        setBack();
    }

    //绘制多边形
    public Polygon DrawRectangular(List<LatLng> list) {
        PolygonOptions polygonOptions = new PolygonOptions();
        polygonOptions.addAll(list);
        polygonOptions.strokeWidth(15) // 多边形的边框
                .strokeColor(getResources().getColor(R.color.A1E0F2)) // 边框颜色
                .fillColor(Color.argb(1, 1, 1, 1));   // 多边形的填充色
        Polygon polygon = aMap.addPolygon(polygonOptions.zIndex(999));
        polygon.setZIndex(999);
        return polygon;
    }

    private void initPermission() {
        if (PermissionUtil.loginPermission(this, LOGINPRESSION)) {
            if (!PermissionUtil.isOPen(ShowLandDescActivity.this)) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, REQEEST_CDOE_GPS);
            } else {
                initLocation();
            }
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rightText:
                InputLandNameDialog dialog = new InputLandNameDialog(this);
                dialog.show();
                dialog.setOnLandNameClickListener(new OnLandNameInputListener() {
                    @Override
                    public void setOnLandNameInputListener(String landName) {
                        if (sizeAll == 0) {
                            showInCommonDialog("请测绘您的土地");
                            return;
                        }
                        String result = "";
                        for (LatLng list : listBGps) {
                            result = result + list.latitude + "," + list.longitude + ";";
                        }

                        LatLng latLng = CenterPointUtil.getCenterPoint(listBGps);
                        LogUtil.e("多边形中心点： " + latLng.longitude + "  " + latLng.latitude);

                    }
                });
                break;
            case R.id.btn_start:
                if (listGps.size() == 0) {
                    Toast.makeText(ShowLandDescActivity.this, "没有获取到GPS坐标!请检查权限!", Toast.LENGTH_SHORT).show();
                    return;
                }
                btn_start.setText("记录中");
                btn_start.setClickable(false);
                tag = true;
                listBGps.add(listGps.get(listGps.size() - 1));
                aMap.addMarker(myAddMarker(listBGps.get(0)));
                break;
            case R.id.btn_extract:
                if (!tag) {
                    Toast.makeText(ShowLandDescActivity.this, "请点击开始按钮!", Toast.LENGTH_SHORT).show();
                    return;
                }
                listBGps.add(listGps.get(listGps.size() - 1));
                if (listBGps != null && listBGps.size() > 1) {
                    //画线
                    List<LatLng> lisas = new ArrayList<>();
                    lisas.add(listBGps.get(listBGps.size() - 2));
                    lisas.add(listBGps.get(listBGps.size() - 1));
                    polyLine(lisas);
                }
                break;
            case R.id.btn_undo:
                if (listLine.size() == 0 || listLine == null) {
                    return;
                }
                listLine.get(listLine.size() - 1).remove();
                listLine.remove(listLine.size() - 1);
                listBGps.remove(listBGps.size() - 1);
                break;
            case R.id.btn_end:
                //画线
                List<LatLng> lisas = new ArrayList<LatLng>();
                lisas.add(listBGps.get(listBGps.size() - 1));
                lisas.add(listBGps.get(0));
                polyLine(lisas);
                //计算面积
                sizeAll = (int) Math.floor(AMapUtils.calculateArea(listBGps) / 666.67);
                textView_map.setText(sizeAll + "");
                break;
            default:
        }
    }

    int sizeAll = 0;

    /**
     * 加载在线瓦片数据
     */
    private void useOMCMap() {
        final String url = "http://www.google.cn/maps/vt?lyrs=y&gl=cn&x=%d&s=&y=%d&z=%d";
        TileOverlayOptions tileOverlayOptions = new TileOverlayOptions().tileProvider(new UrlTileProvider(256, 256) {
            @Override
            public URL getTileUrl(int x, int y, int zoom) {
                try {
                    String mFileDirName;
                    String mFileName;
                    mFileDirName = String.format("L%02d/", zoom + 1);
                    mFileName = String.format("%s", TileXYToQuadKey(x, y, zoom));
                    String LJ = ALBUM_PATH + mFileDirName + mFileName;
                    if (MapImageCache.getInstance().isBitmapExit(mFileDirName + mFileName)) {

                        return new URL("file://" + LJ);
                    } else {
                        String filePath = String.format(url, x, y, zoom);
                        Bitmap mBitmap;
                        mBitmap = getImageBitmap(getImageStream(filePath));
                        try {
                            saveFile(mBitmap, mFileName, mFileDirName);

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return new URL(filePath);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
        tileOverlayOptions.diskCacheEnabled(false).diskCacheDir("/storage/emulated/0/amap/OMCcache").diskCacheSize(1024000).memoryCacheEnabled(true).memCacheSize(102400).zIndex(-9999);
        if (mtileOverlay == null) {
            mtileOverlay = aMap.addTileOverlay(tileOverlayOptions);
        } else {
            LogUtil.e("mtileOverlay为空");
        }

        String[] pointLongs = bean.getPoint().split(";");
        LogUtil.e("1--》" + bean.getPoint());
        try {
            if (pointLongs.length != 0) {
                for (String latlng : Arrays.asList(pointLongs)) {
                    double lat = getDoublePoint(latlng.split(",")[0]);
                    double lng = getDoublePoint(latlng.split(",")[1]);
                    lists.add(new LatLng(lat, lng));
                    LogUtil.e("添加的点" + lat + "  " + lng);
                }
            }
            LogUtil.e("获取点的个数： " + lists.size());
            DrawRectangular(lists);
        } catch (Exception e) {
            LogUtil.e("获取土地经纬度点解析失败");
        }
    }

    public double getDoublePoint(String s) {
        BigDecimal bd = new BigDecimal(s);
        Double d = bd.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
        return d;
    }

    /**
     * 保存文件
     */
    public void saveFile(final Bitmap bm, final String fileName, final String fileDirName) throws IOException {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    if (bm != null) {
                        File dirFile = new File(ALBUM_PATH + fileDirName);
                        if (!dirFile.exists()) {
                            dirFile.mkdir();
                        }
                        File myCaptureFile = new File(ALBUM_PATH + fileDirName + fileName);
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                        bos.flush();
                        bos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        BHThreadPool.getInstance().executeTask(runnable);
    }

    /**
     * 瓦片数据坐标转换
     */
    private String TileXYToQuadKey(int tileX, int tileY, int levelOfDetail) {
        StringBuilder quadKey = new StringBuilder();
        for (int i = levelOfDetail; i > 0; i--) {
            char digit = '0';
            int mask = 1 << (i - 1);
            if ((tileX & mask) != 0) {
                digit++;
            }
            if ((tileY & mask) != 0) {
                digit++;
                digit++;
            }
            quadKey.append(digit);
        }
        return quadKey.toString();
    }

    public InputStream getImageStream(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return conn.getInputStream();
        }
        return null;
    }

    public Bitmap getImageBitmap(InputStream imputStream) {
        // 将所有InputStream写到byte数组当中
        byte[] targetData = null;
        byte[] bytePart = new byte[4096];
        while (true) {
            try {
                int readLength = imputStream.read(bytePart);
                if (readLength == -1) {
                    break;
                } else {
                    byte[] temp = new byte[readLength + (targetData == null ? 0 : targetData.length)];
                    if (targetData != null) {
                        System.arraycopy(targetData, 0, temp, 0, targetData.length);
                        System.arraycopy(bytePart, 0, temp, targetData.length, readLength);
                    } else {
                        System.arraycopy(bytePart, 0, temp, 0, readLength);
                    }
                    targetData = temp;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 指使Bitmap通过byte数组获取数据
        Bitmap bitmap = BitmapFactory.decodeByteArray(targetData, 0, targetData.length);
        return bitmap;
    }


    private void initLocation() {
        mLocationClient = new AMapLocationClient(this);
        mLocationClient.setLocationListener(listener);
        mLocationOption = new AMapLocationClientOption();

        //设置单次定位
        mLocationOption.setOnceLocation(true);
        mLocationOption.setOnceLocationLatest(true);

        //设置多次定位，时间为1000毫秒
        //        mLocationOption.setInterval(1000);

        mLocationOption.setNeedAddress(true);
        mLocationOption.setMockEnable(true);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationClient.startLocation();

        if (aMap == null) {
            aMap = mMapView.getMap();
        }

        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.myLocationType((MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE));//连续定位
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.strokeColor(getResources().getColor(R.color.A1E0F2));
        myLocationStyle.strokeWidth(1);
        myLocationStyle.radiusFillColor(getResources().getColor(R.color.HALFA1E0F2));

        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                //aMap.clear(true);
                //                CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(latLng.latitude, latLng.longitude), 15, 30, 0));
                //                aMap.animateCamera(mCameraUpdate);
                //                aMap.addMarker(myAddMarker(new LatLng(latLng.latitude, latLng.longitude)));
                //拖拽监听
                //                aMap.setOnMarkerDragListener(markerDragListener);
            }
        });
        if (mtileOverlay != null) {
            mtileOverlay.remove();
        }
        useOMCMap();
    }

    public MarkerOptions myAddMarker(LatLng latLng) {
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(new LatLng(latLng.latitude, latLng.longitude));
        markerOption.draggable(true);
        View markerView = LayoutInflater.from(this).inflate(R.layout.view_marker, mMapView, false);
        markerOption.icon(BitmapDescriptorFactory.fromView(markerView));
        //引用drawable中的marker作为地图上的图标
        //        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_activity_gaode_map_location)));
        markerOption.setFlat(false);
        return markerOption;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case LOGINPRESSION:
                initGPS();
                break;
            case REQEEST_CDOE_GPS:
                initLocation();
                break;
            default:
        }
    }

    public void initGPS() {
        if (!PermissionUtil.isOPen(this)) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, REQEEST_CDOE_GPS);
        } else {
            initLocation();
        }

    }

    class MyAMapLocationListener implements AMapLocationListener {
        @Override
        public void onLocationChanged(final AMapLocation aMapLocation) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    if (isShow) {
                        location.setLatitude(aMapLocation.getLatitude());
                        location.setLongitude(aMapLocation.getLongitude());
                        location.setAddress(aMapLocation.getAddress());
                        location.setCountry(aMapLocation.getCountry());
                        location.setCity(aMapLocation.getCity());
                        location.setDistrict(aMapLocation.getDistrict());
                        location.setStreet(aMapLocation.getStreet());
                        location.setStreetNum(aMapLocation.getStreetNum());
                        location.setCityCode(aMapLocation.getCityCode());
                        location.setAdCode(aMapLocation.getAdCode());
                        location.setPoiName(aMapLocation.getPoiName());
                        location.setAoiName(aMapLocation.getAoiName());
                        location.setErrorCode(aMapLocation.getErrorCode());
                        String result = GsonUtil.BeanToJson(location).toString();
                        LogUtil.e(result);
                        listGps.add(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()));
                    }
                }
            };
            BHThreadPool.getInstance().executeTask(runnable);
        }
    }

    public void hua() {
        // 定义多边形的5个点点坐标
        LatLng latLng1 = new LatLng(34.761961, 113.768454);
        LatLng latLng2 = new LatLng(34.763935, 113.780856);
        LatLng latLng3 = new LatLng(34.752476, 113.782659);
        LatLng latLng4 = new LatLng(34.751595, 113.768454);

        // 声明 多边形参数对象
        PolygonOptions polygonOptions = new PolygonOptions();
        // 添加 多边形的每个顶点（顺序添加）
        polygonOptions.add(latLng1, latLng2, latLng3, latLng4);
        polygonOptions.strokeWidth(15) // 多边形的边框
                .strokeColor(Color.argb(50, 1, 1, 1)) // 边框颜色
                .fillColor(Color.argb(1, 1, 1, 1));   // 多边形的填充色
        LogUtil.e("TAGAA", "绘制");
        // 添加一个多边形
        Polygon polygon = aMap.addPolygon(polygonOptions);

    }

    //画线
    public void polyLine(List<LatLng> latLngs) {
        Polyline polyline = aMap.addPolyline(new PolylineOptions().
                addAll(latLngs).width(10).color(Color.argb(255, 255, 0, 0)).zIndex(999));
        listLine.add(polyline);
        //polyline.remove();
    }

    //计算多边形面积
    public static float calculateArea(List<LatLng> points) {
        byte i3 = 3;
        if (points != null && points.size() >= i3) {
            double var2 = 0.0D;
            double var4 = 111319.49079327357D;
            int size = points.size();

            for (int i = 0; i < size; ++i) {
                LatLng var8 = points.get(i);
                LatLng var9 = points.get((i + 1) % size);
                double var10 = var8.longitude * var4 * Math.cos(var8.latitude * 0.017453292519943295D);
                double var12 = var8.latitude * var4;
                double var14 = var9.longitude * var4 * Math.cos(var9.latitude * 0.017453292519943295D);
                double var16 = var9.latitude * var4;
                var2 += var10 * var16 - var14 * var12;
            }

            return (float) Math.abs(var2 / 2.0D);
        } else {
            return 0.0F;
        }
    }
}
